package com.omkarpatil.learningjpa2.mapping.manytoone.jointable;

import javax.persistence.EntityManager;

import com.omkarpatil.learningjpa2.util.EntityManagerFactoryFactory;

public class TestDriver {

	public static void main(String[] args) {
		EntityManager em1 = EntityManagerFactoryFactory.getEntityManagerFactory().createEntityManager();
		em1.getTransaction().begin();
		
		Project projectX = new Project("ProjectX");
		em1.persist(projectX);
		System.out.printf("##### Created one project with id = %s\n", projectX.getId());
		int projectXId = projectX.getId();
		
		Employee jackieChan = new Employee("Jackie Chan");
		jackieChan.setProject(projectX);
		em1.persist(jackieChan);
		System.out.printf("##### Created Jackie Chan with id = %s and assigned to ProjectX\n", jackieChan.getId());
		
		Employee johnTravolta = new Employee("John Travolta");
		johnTravolta.setProject(projectX);
		em1.persist(johnTravolta);
		System.out.printf("##### Created John Travolta with id = %s and assigned to ProjectX\n", johnTravolta.getId());
		int travoltaId = johnTravolta.getId();
		
		System.out.printf("##### Number of people on ProjectX = %s\n", projectX.getEmployees().size());
		em1.getTransaction().commit();
		em1.close();
		
		EntityManager em2 = EntityManagerFactoryFactory.getEntityManagerFactory().createEntityManager();
        em2.getTransaction().begin();
        
        Project projectX2 = em2.find(Project.class, projectXId);
        
        Employee johnyDepp = new Employee("Johny Depp");
        johnyDepp.setProject(projectX2);
        em2.persist(johnyDepp);
        System.out.printf("##### Created Johny Depp with id = %s and assigned to ProjectX\n", johnyDepp.getId());
        
        System.out.printf("##### Number of people on ProjectX = %s\n", projectX2.getEmployees().size());
        
        Employee travolta2 = em2.find(Employee.class, travoltaId);
        System.out.println("##### Deleting Travolta ...");
        em2.remove(travolta2);
        
        em2.getTransaction().commit();
        em2.close();
        
        EntityManager em3 = EntityManagerFactoryFactory.getEntityManagerFactory().createEntityManager();
        em3.getTransaction().begin();
        
        Project projectX3 = em3.find(Project.class, projectXId);
        
        System.out.printf("##### Number of people on ProjectX = %s\n", projectX3.getEmployees().size());
        em3.getTransaction().commit();
        em3.close();
	}
}
